<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
import { getPatientConsultOrderDetailAPI } from '@/apis/consult'
import { useUserStore } from '@/stores/user'
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult'
import { baseURL } from '@/utils/request'
import io from '@hyoga/uni-socket.io'
import { nextTick, ref } from 'vue'
import RoomStatus from './components/room-status.vue'
import type { ChatMsgListData, MsgItem } from '@/types/room'
import PatientInfo from './components/patient-info.vue'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import PrescriptionInfo from './components/prescription-info.vue'
import RateInfo from './components/rate-info.vue'
import { postUploadAPI } from '@/apis/common'
import { useConsultOrderDetail } from '@/hooks'
const props = defineProps<{
  orderId: string
  payResult: string
}>()

const store = useUserStore()
// 创建 socket 实例
const socket = io(baseURL, {
  // 传递 token，用于身份认证（后端要求）
  auth: { token: `Bearer ${store.token}` },
  // 传递订单 id，用于查询订单信息（后端要求）
  query: { orderId: props.orderId },
  // 支持 websocket 和 轮询 两种传输方式
  transports: ['websocket', 'polling'],
  // 连接超时时间
  timeout: 5000,
})
// // 问诊订单详情
// const orderDetail = ref<GetPatientConsultOrderDetailData>()
// // 获取问诊订单详情
// async function getOrderDetail() {
//   const res = await getPatientConsultOrderDetailAPI(props.orderId)
//   // console.log('获取订单详情', res)
//   orderDetail.value = res.data
// }
// getOrderDetail()

const { orderDetail, getOrderDetail } = useConsultOrderDetail(props.orderId)

// 监听连接成功事件
socket.on('connect', () => {
  console.log('连接成功')
})

// 监听订单状态变化，statusChange 为后端定义的事件名称
socket.on('statusChange', (data) => {
  console.log('收到消息', data)
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})

// 消息列表
const msgList = ref<MsgItem[]>([])
// 2. 获取历史消息，后端定义的事件名称为 chatMsgList
socket.on('chatMsgList', (res: ChatMsgListData) => {
  // 业务状态码异常退出
  if (res.code !== 10000) return
  // 循环消息组（消息组按时间节点划分，一个消息组包含多个消息）
  res.data?.forEach((item) => {
    // 如果有消息列表，则追加到数组中
    if (item.items) {
      msgList.value.push(
        //前添加一条普通信息 作为消息组时间
        {
          msgType: 31,
          createTime: item.createTime,
          msg: {
            content: item.createTime,
          },
        },
        //消息组中的时间
        ...item.items!
      )
    }
  })
})

// 3. 接收回复消息，后端定义的事件名称为 receiveChatMsg
socket.on('receiveChatMsg', async (res: MsgItem) => {
  // 追加到消息数组中
  msgList.value.push(res)
  // 通知后端，前端消息已读
  socket.emit('updateMsgStatus', res.id)
  // 通过 nextTick 等待消息列表更新
  await nextTick()
  // 接收信息后 滚动最新消息
  scrollIntoView.value = `id-${res.id}`
})

// 监听连接失败事件
socket.on('disconnect', () => {
  console.log('连接失败')
})

//4.发送消息
const textMessage = ref('')
const sendMessage = () => {
  //空判断
  if (textMessage.value.trim() === '') {
    uni.showToast({
      title: '请输入内容',
      icon: 'none',
    })
    return
  }
  // 调用后端接口发送消息
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: 1,
    msg: {
      content: textMessage.value,
    },
  })
  // 清空输入框
  textMessage.value = ''
}

//5.发送图片信息
const handleUploadImage = async () => {
  //5.1 非咨询状态 不能发送信息图片
  if (orderDetail.value?.status !== OrderStatus.ZiXunZhong) {
    uni.showToast({
      title: '非咨询状态 不能发送信息图片',
      icon: 'none',
    })
    return
  }

  //5.2 选择图片(支持相册和相机)
  const { tempFilePaths } = await uni.chooseImage({
    count: 1, // 选择图片数量
    sizeType: ['original', 'compressed'], // 图片类型
    sourceType: ['album', 'camera'], // 图片来源
  })
  //5.3 上传图片
  const res = await postUploadAPI(tempFilePaths[0])

  //5.4 通过 WS 发送图片信息
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id, //发送者
    to: orderDetail.value?.docInfo?.id, //接收者(医生)
    msgType: 4, //消息类型
    msg: {
      picture: res.data, //图片信息
    },
  })
}

// 滚动到最底部
const scrollIntoView = ref('')
</script>

<template>
  <view class="room-page">
    <!-- 咨询室状态组件 -->
    <RoomStatus
      v-if="orderDetail"
      :status="orderDetail?.status"
      :statusValue="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <!-- 消息列表 -->
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoView"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="item in msgList" :key="item.id" :id="`id-${item.id}`">
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord!" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 32" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <PrescriptionInfo v-else-if="item.msgType === 22" :prescr="item.msg?.prescription!" />
          <RateInfo
            v-else-if="item.msgType === 23"
            :order-id="props.orderId"
            :doctor-id="orderDetail?.docInfo?.id"
          />
          <!-- 医生评价（已评价） -->
          <RateInfo :evaluateDoc="item.msg?.evaluateDoc" has-evaluate v-if="item.msgType === 24" />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          @click="sendMessage"
          v-model="textMessage"
          :disabled="orderDetail?.status !== OrderStatus.ZiXunZhong"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="handleUploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
